package com.otp.webapp.action.util;

import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.FacesContext;
import javax.faces.FacesException;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;
import javax.faces.application.NavigationHandler;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;




public class CustomExceptionHandler extends ExceptionHandlerWrapper{
	
    //private static final Logger log = Logger.getLogger(CustomExceptionHandler.class.getCanonicalName());
    private ExceptionHandler wrapped;
 
    CustomExceptionHandler(ExceptionHandler exception) {
        this.wrapped = exception;
    }
 
    @Override
    public ExceptionHandler getWrapped() {
        return wrapped;
    }
 
    @Override
    public void handle() throws FacesException {
    	
		ResourceBundle environmentSpecific = ResourceBundle.getBundle("env");
		String homeFolder = environmentSpecific.getString("home");

		
        final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
        while (i.hasNext()) {
            ExceptionQueuedEvent event = i.next();
            ExceptionQueuedEventContext context =
                    (ExceptionQueuedEventContext) event.getSource();
 
            // get the exception from context
            Throwable t = context.getException();
 
            final FacesContext fc = FacesContext.getCurrentInstance();
            final Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
            Map<String, Object> sessionMap = fc.getExternalContext().getSessionMap();

            final NavigationHandler nav = fc.getApplication().getNavigationHandler();
            
            String viewId = fc.getViewRoot().getViewId();
            System.out.println("View id is "+viewId);

            try {
 
                //log error ?
                //log.log(Level.SEVERE, "Critical Exception!", t);
 
                //redirect error page
                requestMap.put("exceptionMessage", t.getMessage());
                sessionMap.put("GLOBAL_RENDER_ERROR", t);
        		String errorPath = homeFolder+"/errorPage.jsf";
                nav.handleNavigation(fc, null, errorPath);
                fc.renderResponse();
                
                // remove the comment below if you want to report the error in a jsf error message
                //JsfUtil.addErrorMessage(t.getMessage());
 
            } finally {
                //remove it from queue
                i.remove();
            }
        }
        //parent handle
        getWrapped().handle();
    }

}
